﻿using System;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using PortalWeb.CMS.Core.Entity;
using PortalWeb.CMS.Core.IManager;
using PortalWeb.Core.Entity;
using PortalWeb.Models.Cms;
using System.Threading.Tasks;

namespace PortalWeb.Areas.CmsAdmin.Controllers
{
    [Authorize]
    public class ArticleController : Controller
    {
        public ICommonModelManager CommonModelManager { get; }
        public IArticleManager ArticleManager { get; }
        public IAttachmentManager AttachmentManager { get; }
        public ArticleController(IArticleManager articleManager, IAttachmentManager attachmentManager, ICommonModelManager commonModelManager)
        {
            ArticleManager = articleManager;
            AttachmentManager = attachmentManager;
            CommonModelManager = commonModelManager;
        }
      
        // GET: /Admin/News/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Article article = ArticleManager.Get(id);
            if (article == null)
            {
                return HttpNotFound();
            }
            return View(new ArticleViewModel(article));
        }

        // GET: /Admin/News/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: /Admin/News/Create
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性，有关 
        // 详细信息，请参阅 http://go.microsoft.com/fwlink/?LinkId=317598。
        [ValidateInput(false)]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Article article)
        {
            article.CommonModel = new CommonModel();
            TryUpdateModel(article.CommonModel, new[] { "CategoryId", "Title", "DefaultPicUrl" });
            if (ModelState.IsValid)
            {
                //设置固定值
                article.CommonModel.Hits = 0;
                article.CommonModel.Inputer = User.Identity.Name;
                article.CommonModel.Model = "Article";
                article.CommonModel.ReleaseDate = DateTime.Now;
                article.CommonModel.Status = 99;
                article = ArticleManager.Add(article);
                if (article.Id > 0)
                {
                    //查询相关附件
                    var attachments = AttachmentManager.FindList(null, User.Identity.Name, string.Empty).ToList();
                    //遍历附件
                    foreach (var att in attachments)
                    {
                        var filePath = Url.Content(att.FileParth);
                        //文章首页图片或内容中使用了该附件则更改ModelID为文章保存后的ModelID
                        if ((article.CommonModel.DefaultPicUrl != null &&
                             article.CommonModel.DefaultPicUrl.IndexOf(filePath, StringComparison.Ordinal) >= 0) ||
                            article.Content.IndexOf(filePath, StringComparison.Ordinal) > 0)
                        {
                            att.ModelId = article.Id;
                            AttachmentManager.Update(att);
                        }
                        else
                        {
                            //未使用改附件则删除附件和数据库中的记录
                            System.IO.File.Delete(Server.MapPath(att.FileParth));
                            AttachmentManager.Delete(att);
                        }
                    }
                    return View("AddSucess", new ArticleViewModel(article));
                }
            }
            return View(new ArticleViewModel(article));
        }

        // GET: /Admin/News/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Article article = ArticleManager.Get(id);
            if (article == null)
            {
                return HttpNotFound();
            }
            return View(new ArticleViewModel(article));
        }

        // POST: /Admin/News/Edit/5
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性，有关 
        // 详细信息，请参阅 http://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateInput(false)]
        [ValidateAntiForgeryToken]
        public ActionResult Edit()
        {
            int id = int.Parse(ControllerContext.RouteData.GetRequiredString("id"));
            var article = ArticleManager.Get(id);
            TryUpdateModel(article, new string[] {"Author", "Source", "Intro", "Content"});
            TryUpdateModel(article.CommonModel,new string[] {"CategoryId", "Title", "DefaultPicUrl"});
            // "CommonModel", 
            if (ModelState.IsValid)
            {
                if (ArticleManager.Update(article))
                {
                    //附件处理
                    var attachments =
                        AttachmentManager.FindList(article.CommonModel.Id, User.Identity.Name, string.Empty, true)
                            .ToList();
                    foreach (var att in attachments)
                    {
                        var filePath = Url.Content(att.FileParth);
                        if ((article.CommonModel.DefaultPicUrl != null &&
                             article.CommonModel.DefaultPicUrl.IndexOf(filePath) >= 0) ||
                            article.Content.IndexOf(filePath) > 0)
                        {
                            att.ModelId = article.Id;
                            AttachmentManager.Update(att);
                        }
                        else
                        {
                            System.IO.File.Delete(Server.MapPath(att.FileParth));
                            AttachmentManager.Delete(att);
                        }
                    }
                    return View("EditSucess", new ArticleViewModel(article));
                }
            }
            return View(new ArticleViewModel(article));
        }

        /// <summary>
        /// 全部文章
        /// </summary>
        /// <returns></returns>
        [Authorize(Roles = RoleConst.ADMINISTRATOR)]
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 文章列表Json【注意权限问题，普通人员是否可以访问？】
        /// </summary>
        /// <param name="title">标题</param>
        /// <param name="input">录入</param>
        /// <param name="category">栏目</param>
        /// <param name="fromDate">日期起</param>
        /// <param name="toDate">日期止</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页记录</param>
        /// <returns></returns>
        public async Task<JsonResult> JsonList(string title, string input, int? category, DateTime? fromDate,
            DateTime? toDate,
            int pageIndex = 1, int pageSize = 20)
        {
            if (category == null)
                category = 0;
            int offset = (pageIndex - 1)*pageSize;
            int limit = pageSize*pageIndex;
            var rows = from cm in
                await CommonModelManager.LoadPageEntitiesAsync(p => p.Model == "Article", false, p => p.ReleaseDate,
                    offset, limit)
                select new CommonModelViewModel()
                {
                    Id = cm.Id,
                    Inputer = cm.Inputer,
                    Hits = cm.Hits,
                    ReleaseDate = cm.ReleaseDate,
                    CategoryId = cm.Category.Id,
                    CategoryName = cm.Category.Name,
                    DefaultPicUrl = cm.DefaultPicUrl,
                    Title = cm.Title,
                    Status = cm.Status
                };

            return Json(new {total = CommonModelManager.Count(), rows = rows.ToList()});
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id">文章id</param>
        /// <returns></returns>
        public JsonResult Delete(int id)
        {
            //删除附件
            var article = ArticleManager.Get(id);
            if (article == null) return Json(false);
            //附件列表
            var attachmentList = article.CommonModel.Attachment;
            var commonModel = CommonModelManager.Get(id);
            //删除文章
            if (ArticleManager.Delete(article))
            {
                //删除附件文件
                foreach (var attachment in attachmentList)
                {
                    System.IO.File.Delete(Server.MapPath(attachment.FileParth));
                }
                //删除公共模型
                CommonModelManager.Delete(commonModel);
                return Json(true);
            }
            else return Json(false);
        }
    }
}
